home *** CD-ROM | disk | FTP | other *** search
/ Aminet 1 (Walnut Creek) / Aminet - June 1993 [Walnut Creek].iso / aminet / util / gnu / textutl3.lha / textutils-1.3 / src / tr.c < prev    next >
C/C++ Source or Header  |  1992-06-29  |  49KB  |  1,805 lines

  1. /* tr -- a filter to translate characters
  2.    Copyright (C) 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Jim Meyering. */
  19.  
  20. #define _GNU_SOURCE
  21. #include <ctype.h>
  22. #ifndef isblank
  23. #define isblank(c) ((c) == ' ' || (c) == '\t')
  24. #endif
  25. #ifndef isgraph
  26. #define isgraph(c) (isprint (c) && !isspace (c))
  27. #endif
  28. #include <stdio.h>
  29. #include <assert.h>
  30. #include <errno.h>
  31. #include <sys/types.h>
  32. #include "getopt.h"
  33. #include "system.h"
  34.  
  35. #ifndef LONG_MAX
  36. #define LONG_MAX 0x7FFFFFFF
  37. #endif
  38.  
  39. #ifndef UCHAR_MAX
  40. #define UCHAR_MAX 0xFF
  41. #endif
  42.  
  43. #define N_CHARS (UCHAR_MAX + 1)
  44.  
  45. /* A pointer to a function that returns an int. */
  46. typedef int (*PFI) ();
  47.  
  48. /* Convert from character C to its index in the collating
  49.    sequence array.  Just cast to an unsigned int to avoid
  50.    problems with sign-extension. */
  51. #define ORD(c) (unsigned int)(c)
  52.  
  53. /* The inverse of ORD. */
  54. #define CHR(i) (unsigned char)(i)
  55.  
  56. /* The value for Spec_list->state that indicates to
  57.    get_next that it should initialize the tail pointer.
  58.    Its value doesn't matter as long as it can't be
  59.    confused with a valid character code. */
  60. #define BEGIN_STATE (2 * N_CHARS)
  61.  
  62. /* The value for Spec_list->state that indicates to
  63.    get_next that the element pointed to by Spec_list->tail is
  64.    being considered for the first time on this pass through the
  65.    list -- it indicates that get_next should make any necessary
  66.    initializations. */
  67. #define NEW_ELEMENT (BEGIN_STATE + 1)
  68.  
  69. /* A value distinct from any character that may have been stored in a
  70.    buffer as the result of a block-read in the function squeeze_filter. */
  71. #define NOT_A_CHAR (unsigned int)(-1)
  72.  
  73. /* The following (but not CC_NO_CLASS) are indices into the array of
  74.    valid character class strings. */
  75. enum Char_class
  76. {
  77.   CC_ALNUM = 0, CC_ALPHA = 1, CC_BLANK = 2, CC_CNTRL = 3,
  78.   CC_DIGIT = 4, CC_GRAPH = 5, CC_LOWER = 6, CC_PRINT = 7,
  79.   CC_PUNCT = 8, CC_SPACE = 9, CC_UPPER = 10, CC_XDIGIT = 11,
  80.   CC_NO_CLASS = 9999
  81. };
  82.  
  83. /* Character class to which a character (returned by get_next) belonged;
  84.    but it is set only if the construct from which the character was obtained
  85.    was one of the character classes [:upper:] or [:lower:].  The value
  86.    is used only when translating and then, only to make sure that upper
  87.    and lower class constructs have the same relative positions in string1
  88.    and string2. */
  89. enum Upper_Lower_class
  90. {
  91.   UL_LOWER = 0,
  92.   UL_UPPER = 1,
  93.   UL_NONE = 2
  94. };
  95.  
  96. /* A shortcut to ensure that when constructing the translation array,
  97.    one of the values returned by paired calls to get_next (from s1 and s2) is
  98.    from [:upper:] and the other is from [:lower:], or neither is
  99.    from upper or lower.  In fact, no other character classes are allowed
  100.    when translating, but that condition is tested elsewhere.  This array
  101.    is indexed by values of type enum Upper_Lower_class. */
  102. static int class_ok[3][3] =
  103. {
  104.   {0, 1, 0},
  105.   {1, 0, 0},
  106.   {0, 0, 1}
  107. };
  108.  
  109. /* The type of a List_element.  See build_spec_list for more details. */
  110. enum Range_element_type
  111. {
  112.   RE_NO_TYPE = 0,
  113.   RE_NORMAL_CHAR,
  114.   RE_RANGE,
  115.   RE_CHAR_CLASS,
  116.   RE_EQUIV_CLASS,
  117.   RE_REPEATED_CHAR
  118. };
  119.  
  120. /* One construct in one of tr's argument strings.
  121.    For example, consider the POSIX version of the
  122.    classic tr command:
  123.        tr -cs 'a-zA-Z_' '[\n*]'
  124.    String1 has 3 constructs, two of which are ranges (a-z and A-Z),
  125.    and a single normal character, `_'.  String2 has one construct. */
  126. struct List_element
  127. {
  128.   enum Range_element_type type;
  129.   struct List_element *next;
  130.   union
  131.   {
  132.     int normal_char;
  133.     struct            /* unnamed */
  134.     {
  135.       unsigned int first_char;
  136.       unsigned int last_char;
  137.     } range;
  138.     enum Char_class char_class;
  139.     int equiv_code;
  140.     struct            /* unnamed */
  141.     {
  142.       unsigned int the_repeated_char;
  143.       long repeat_count;
  144.     } repeated_char;
  145.   } u;
  146. };
  147.  
  148. /* Each of tr's argument strings is parsed into a form that is easier
  149.    to work with: a linked list of constructs (struct List_element).
  150.    Each Spec_list structure also encapsulates various attributes of
  151.    the corresponding argument string.  The attributes are used mainly
  152.    to verify that the strings are legal in the context of any options
  153.    specified (like -s, -d, or -c).  The main exception is the member
  154.    `tail', which is first used to construct the list.  After construction,
  155.    it is used by get_next to save its state when traversing the list.
  156.    The member `state' serves a similar function. */
  157. struct Spec_list
  158. {
  159.   /* Points to the head of the list of range elements.
  160.      The first struct is a dummy; its members are never used. */
  161.   struct List_element *head;
  162.  
  163.   /* When appending, points to the last element.  When traversing via
  164.      get_next(), points to the element to process next.  Setting
  165.      Spec_list.state to the value BEGIN_STATE before calling get_next
  166.      signals get_next to initialize tail to point to head->next. */
  167.   struct List_element *tail;
  168.  
  169.   /* Used to save state between calls to get_next(). */
  170.   unsigned int state;
  171.  
  172.   /* Length, in the sense that length('a-z[:digit:]123abc')
  173.      is 42 ( = 26 + 10 + 6). */
  174.   int length;
  175.  
  176.   /* The number of [c*] and [c*0] constructs that appear in this spec. */
  177.   int n_indefinite_repeats;
  178.  
  179.   /* Non-zero if this spec contains at least one equivalence
  180.      class construct e.g. [=c=]. */
  181.   int has_equiv_class;
  182.  
  183.   /* Non-zero if this spec contains at least one of [:upper:] or
  184.      [:lower:] class constructs. */
  185.   int has_upper_or_lower;
  186.  
  187.   /* Non-zero if this spec contains at least one of the character class
  188.      constructs (all but upper and lower) that aren't allowed in s2. */
  189.   int has_restricted_char_class;
  190. };
  191.  
  192. char *xmalloc ();
  193. char *stpcpy ();
  194. void error ();
  195.  
  196. /* The name by which this program was run. */
  197. char *program_name;
  198.  
  199. /* When non-zero, each sequence in the input of a repeated character
  200.    (call it c) is replaced (in the output) by a single occurrence of c
  201.    for every c in the squeeze set. */
  202. static int squeeze_repeats = 0;
  203.  
  204. /* When non-zero, removes characters in the delete set from input. */
  205. static int delete = 0;
  206.  
  207. /* Use the complement of set1 in place of set1. */
  208. static int complement = 0;
  209.  
  210. /* When non-zero, this flag causes GNU tr to provide strict
  211.    compliance with POSIX draft 1003.2.11.2.  The POSIX spec
  212.    says that when -d is used without -s, string2 (if present)
  213.    must be ignored.  Silently ignoring arguments is a bad idea.
  214.    The default GNU behavior is to give a usage message and exit.
  215.    Additionally, when this flag is non-zero, tr prints warnings
  216.    on stderr if it is being used in a manner that is not portable.
  217.    Applicable warnings are given by default, but are suppressed
  218.    if the environment variable `POSIXLY_CORRECT' is set, since
  219.    being POSIX conformant means we can't issue such messages.
  220.    Warnings on the following topics are suppressed when this
  221.    variable is non-zero:
  222.    1. Ambiguous octal escapes. */
  223. static int posix_pedantic;
  224.  
  225. /* When tr is performing translation and string1 is longer than string2,
  226.    POSIX says that the result is undefined.  That gives the implementor
  227.    of a POSIX conforming version of tr two reasonable choices for the
  228.    semantics of this case.
  229.  
  230.    * The BSD tr pads string2 to the length of string1 by
  231.    repeating the last character in string2.
  232.  
  233.    * System V tr ignores characters in string1 that have no
  234.    corresponding character in string2.  That is, string1 is effectively
  235.    truncated to the length of string2.
  236.  
  237.    When non-zero, this flag causes GNU tr to imitate the behavior
  238.    of System V tr when translating with string1 longer than string2.
  239.    The default is to emulate BSD tr.  This flag is ignored in modes where
  240.    no translation is performed.  Emulating the System V tr
  241.    in this exceptional case causes the relatively common BSD idiom:
  242.  
  243.        tr -cs A-Za-z0-9 '\012'
  244.  
  245.    to break (it would convert only zero bytes, rather than all
  246.    non-alphanumerics, to newlines).
  247.  
  248.    WARNING: This switch does not provide general BSD or System V
  249.    compatibility.  For example, it doesn't disable the interpretation
  250.    of the POSIX constructs [:alpha:], [=c=], and [c*10], so if by
  251.    some unfortunate coincidence you use such constructs in scripts
  252.    expecting to use some other version of tr, the scripts will break. */
  253. static int truncate_set1 = 0;
  254.  
  255. /* An alias for (!delete && non_option_args == 2).
  256.    It is set in main and used there and in validate(). */
  257. static int translating;
  258.  
  259. #ifndef BUFSIZ
  260. #define BUFSIZ 8192
  261. #endif
  262.  
  263. #define IO_BUF_SIZE BUFSIZ
  264. static unsigned char io_buf[IO_BUF_SIZE];
  265.  
  266. char *char_class_name[] =
  267. {
  268.   "alnum", "alpha", "blank", "cntrl", "digit", "graph",
  269.   "lower", "print", "punct", "space", "upper", "xdigit"
  270. };
  271. #define N_CHAR_CLASSES (sizeof(char_class_name) / sizeof(char_class_name[0]))
  272.  
  273. typedef char SET_TYPE;
  274.  
  275. /* Array of boolean values.  A character `c' is a member of the
  276.    squeeze set if and only if in_squeeze_set[c] is true.  The squeeze
  277.    set is defined by the last (possibly, the only) string argument
  278.    on the command line when the squeeze option is given.  */
  279. static SET_TYPE in_squeeze_set[N_CHARS];
  280.  
  281. /* Array of boolean values.  A character `c' is a member of the
  282.    delete set if and only if in_delete_set[c] is true.  The delete
  283.    set is defined by the first (or only) string argument on the
  284.    command line when the delete option is given.  */
  285. static SET_TYPE in_delete_set[N_CHARS];
  286.  
  287. /* Array of character values defining the translation (if any) that
  288.    tr is to perform.  Translation is performed only when there are
  289.    two specification strings and the delete switch is not given. */
  290. static char xlate[N_CHARS];
  291.  
  292. static struct option long_options[] =
  293. {
  294.   {"complement", 0, NULL, 'c'},
  295.   {"delete", 0, NULL, 'd'},
  296.   {"squeeze-repeats", 0, NULL, 's'},
  297.   {"truncate-set1", 0, NULL, 't'},
  298.   {NULL, 0, NULL, 0}
  299. };
  300.  
  301.  
  302. static void
  303. usage ()
  304. {
  305.   fprintf (stderr, "\
  306. Usage: %s [-cdst] [--complement] [--delete] [--squeeze-repeats]\n\
  307.        [--truncate-set1] string1 [string2]\n",
  308.        program_name);
  309.   exit (2);
  310. }
  311.  
  312. /* Return non-zero if the character C is a member of the
  313.    equivalence class containing the character EQUIV_CLASS. */
  314.  
  315. static int
  316. is_equiv_class_member (equiv_class, c)
  317.      unsigned int equiv_class;
  318.      unsigned int c;
  319. {
  320.   return (equiv_class == c);
  321. }
  322.  
  323. /* Return non-zero if the character C is a member of the
  324.    character class CHAR_CLASS. */
  325.  
  326. static int
  327. is_char_class_member (char_class, c)
  328.      enum Char_class char_class;
  329.      unsigned int c;
  330. {
  331.   switch (char_class)
  332.     {
  333.     case CC_ALNUM:
  334.       return isalnum (c);
  335.       break;
  336.     case CC_ALPHA:
  337.       return isalpha (c);
  338.       break;
  339.     case CC_BLANK:
  340.       return isblank (c);
  341.       break;
  342.     case CC_CNTRL:
  343.       return iscntrl (c);
  344.       break;
  345.     case CC_DIGIT:
  346.       return isdigit (c);
  347.       break;
  348.     case CC_GRAPH:
  349.       return isgraph (c);
  350.       break;
  351.     case CC_LOWER:
  352.       return islower (c);
  353.       break;
  354.     case CC_PRINT:
  355.       return isprint (c);
  356.       break;
  357.     case CC_PUNCT:
  358.       return ispunct (c);
  359.       break;
  360.     case CC_SPACE:
  361.       return isspace (c);
  362.       break;
  363.     case CC_UPPER:
  364.       return isupper (c);
  365.       break;
  366.     case CC_XDIGIT:
  367.       return isxdigit (c);
  368.       break;
  369.     case CC_NO_CLASS:
  370.       abort ();
  371.       return 0;
  372.       break;
  373.     }
  374. }
  375.  
  376. /* Perform the first pass over each range-spec argument S,
  377.    converting all \c and \ddd escapes to their one-byte representations.
  378.    The conversion is done in-place, so S must point to writable
  379.    storage.  If an illegal quote sequence is found, an error message is
  380.    printed and the function returns non-zero.  Otherwise the length of
  381.    the resulting string is returned through LEN and the function returns 0.
  382.    The resulting array of characters may contain zero-bytes; however,
  383.    on input, S is assumed to be null-terminated, and hence
  384.    cannot contain actual (non-escaped) zero bytes. */
  385.  
  386. static int
  387. unquote (s, len)
  388.      unsigned char *s;
  389.      int *len;
  390. {
  391.   int i, j;
  392.  
  393.   j = 0;
  394.   for (i = 0; s[i]; i++)
  395.     {
  396.       switch (s[i])
  397.     {
  398.       int c;
  399.     case '\\':
  400.       switch (s[i + 1])
  401.         {
  402.           int oct_digit;
  403.         case '\\':
  404.           c = '\\';
  405.           break;
  406.         case 'a':
  407.           c = '\007';
  408.           break;
  409.         case 'b':
  410.           c = '\b';
  411.           break;
  412.         case 'f':
  413.           c = '\f';
  414.           break;
  415.         case 'n':
  416.           c = '\n';
  417.           break;
  418.         case 'r':
  419.           c = '\r';
  420.           break;
  421.         case 't':
  422.           c = '\t';
  423.           break;
  424.         case 'v':
  425.           c = '\v';
  426.           break;
  427.         case '0':
  428.         case '1':
  429.         case '2':
  430.         case '3':
  431.         case '4':
  432.         case '5':
  433.         case '6':
  434.         case '7':
  435.           c = s[i + 1] - '0';
  436.           oct_digit = s[i + 2] - '0';
  437.           if (0 <= oct_digit && oct_digit <= 7)
  438.         {
  439.           c = 8 * c + oct_digit;
  440.           ++i;
  441.           oct_digit = s[i + 2] - '0';
  442.           if (0 <= oct_digit && oct_digit <= 7)
  443.             {
  444.               if (8 * c + oct_digit < N_CHARS)
  445.             {
  446.               c = 8 * c + oct_digit;
  447.               ++i;
  448.             }
  449.               else if (!posix_pedantic)
  450.             {
  451.               /* Any octal number larger than 0377 won't
  452.                  fit in 8 bits.  So we stop when adding the
  453.                  next digit would put us over the limit and
  454.                  give a warning about the ambiguity.  POSIX
  455.                  isn't clear on this, but one person has said
  456.                  that in his interpretation, POSIX says tr
  457.                  can't even give a warning. */
  458.               error (0, 0, "warning: the ambiguous octal escape \
  459. \\%c%c%c is being\n\tinterpreted as the 2-byte sequence \\0%c%c, `%c'",
  460.                  s[i], s[i + 1], s[i + 2],
  461.                  s[i], s[i + 1], s[i + 2]);
  462.             }
  463.             }
  464.         }
  465.           break;
  466.         case '\0':
  467.           error (0, 0, "invalid backslash escape at end of string");
  468.           return 1;
  469.           break;
  470.         default:
  471.           error (0, 0, "invalid backslash escape `\\%c'", s[i + 1]);
  472.           return 1;
  473.           break;
  474.         }
  475.       ++i;
  476.       s[j++] = c;
  477.       break;
  478.     default:
  479.       s[j++] = s[i];
  480.       break;
  481.     }
  482.     }
  483.   *len = j;
  484.   return 0;
  485. }
  486.  
  487. /* If CLASS_STR is a valid character class string, return its index
  488.    in the global char_class_name array.  Otherwise, return CC_NO_CLASS. */
  489.  
  490. static enum Char_class
  491. look_up_char_class (class_str)
  492.      unsigned char *class_str;
  493. {
  494.   unsigned int i;
  495.  
  496.   for (i = 0; i < N_CHAR_CLASSES; i++)
  497.     if (strcmp (class_str, char_class_name[i]) == 0)
  498.       return (enum Char_class) i;
  499.   return CC_NO_CLASS;
  500. }
  501.  
  502. /* Return a newly allocated string with a printable version of C.
  503.    This function is used solely for formatting error messages. */
  504.  
  505. static char *
  506. make_printable_char (c)
  507.      unsigned int c;
  508. {
  509.   char *buf = xmalloc (5);
  510.  
  511.   assert (c < N_CHARS);
  512.   if (isprint (c))
  513.     {
  514.       buf[0] = c;
  515.       buf[1] = '\0';
  516.     }
  517.   else
  518.     {
  519.       sprintf (buf, "\\%03o", c);
  520.     }
  521.   return buf;
  522. }
  523.  
  524. /* Return a newly allocated copy of S which is suitable for printing.
  525.    LEN is the number of characters in S.  Most non-printing
  526.    (isprint) characters are represented by a backslash followed by
  527.    3 octal digits.  However, the characters represented by \c escapes
  528.    where c is one of [abfnrtv] are represented by their 2-character \c
  529.    sequences.  This function is used solely for printing error messages. */
  530.  
  531. static char *
  532. make_printable_str (s, len)
  533.      unsigned char *s;
  534.      int len;
  535. {
  536.   /* Worst case is that every character expands to a backslash
  537.      followed by a 3-character octal escape sequence. */
  538.   char *printable_buf = xmalloc (4 * len + 1);
  539.   char *p = printable_buf;
  540.   int i;
  541.  
  542.   for (i = 0; i < len; i++)
  543.     {
  544.       char buf[5];
  545.       char *tmp = NULL;
  546.  
  547.       switch (s[i])
  548.     {
  549.     case '\\':
  550.       tmp = "\\";
  551.       break;
  552.     case '\007':
  553.       tmp = "\\a";
  554.       break;
  555.     case '\b':
  556.       tmp = "\\b";
  557.       break;
  558.     case '\f':
  559.       tmp = "\\f";
  560.       break;
  561.     case '\n':
  562.       tmp = "\\n";
  563.       break;
  564.     case '\r':
  565.       tmp = "\\r";
  566.       break;
  567.     case '\t':
  568.       tmp = "\\t";
  569.       break;
  570.     case '\v':
  571.       tmp = "\\v";
  572.       break;
  573.     default:
  574.       if (isprint (s[i]))
  575.         {
  576.           buf[0] = s[i];
  577.           buf[1] = '\0';
  578.         }
  579.       else
  580.         sprintf (buf, "\\%03o", s[i]);
  581.       tmp = buf;
  582.       break;
  583.     }
  584.       p = stpcpy (p, tmp);
  585.     }
  586.   return printable_buf;
  587. }
  588.  
  589. /* Append a newly allocated structure representing a
  590.    character C to the specification list LIST. */
  591.  
  592. static void
  593. append_normal_char (list, c)
  594.      struct Spec_list *list;
  595.      unsigned int c;
  596. {
  597.   struct List_element *new;
  598.  
  599.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  600.   new->next = NULL;
  601.   new->type = RE_NORMAL_CHAR;
  602.   new->u.normal_char = c;
  603.   assert (list->tail);
  604.   list->tail->next = new;
  605.   list->tail = new;
  606. }
  607.  
  608. /* Append a newly allocated structure representing the range
  609.    of characters from FIRST to LAST to the specification list LIST.
  610.    Return non-zero if LAST precedes FIRST in the collating sequence,
  611.    zero otherwise.  This means that '[c-c]' is acceptable.  */
  612.  
  613. static int
  614. append_range (list, first, last)
  615.      struct Spec_list *list;
  616.      unsigned int first;
  617.      unsigned int last;
  618. {
  619.   struct List_element *new;
  620.  
  621.   if (ORD (first) > ORD (last))
  622.     {
  623.       char *tmp1 = make_printable_char (first);
  624.       char *tmp2 = make_printable_char (last);
  625.  
  626.       error (0, 0,
  627.          "range-endpoints of `%s-%s' are in reverse collating sequence order",
  628.          tmp1, tmp2);
  629.       free (tmp1);
  630.       free (tmp2);
  631.       return 1;
  632.     }
  633.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  634.   new->next = NULL;
  635.   new->type = RE_RANGE;
  636.   new->u.range.first_char = first;
  637.   new->u.range.last_char = last;
  638.   assert (list->tail);
  639.   list->tail->next = new;
  640.   list->tail = new;
  641.   return 0;
  642. }
  643.  
  644. /* If CHAR_CLASS_STR is a valid character class string, append a
  645.    newly allocated structure representing that character class to the end
  646.    of the specification list LIST and return 0.  If CHAR_CLASS_STR is not
  647.    a valid string, give an error message and return non-zero. */
  648.  
  649. static int
  650. append_char_class (list, char_class_str, len)
  651.      struct Spec_list *list;
  652.      unsigned char *char_class_str;
  653.      int len;
  654. {
  655.   enum Char_class char_class;
  656.   struct List_element *new;
  657.  
  658.   char_class = look_up_char_class (char_class_str);
  659.   if (char_class == CC_NO_CLASS)
  660.     {
  661.       char *tmp = make_printable_str (char_class_str, len);
  662.  
  663.       error (0, 0, "invalid character class `%s'", tmp);
  664.       free (tmp);
  665.       return 1;
  666.     }
  667.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  668.   new->next = NULL;
  669.   new->type = RE_CHAR_CLASS;
  670.   new->u.char_class = char_class;
  671.   assert (list->tail);
  672.   list->tail->next = new;
  673.   list->tail = new;
  674.   return 0;
  675. }
  676.  
  677. /* Append a newly allocated structure representing a [c*n]
  678.    repeated character construct, to the specification list LIST.
  679.    THE_CHAR is the single character to be repeated, and REPEAT_COUNT
  680.    is non-negative repeat count. */
  681.  
  682. static void
  683. append_repeated_char (list, the_char, repeat_count)
  684.      struct Spec_list *list;
  685.      unsigned int the_char;
  686.      long int repeat_count;
  687. {
  688.   struct List_element *new;
  689.  
  690.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  691.   new->next = NULL;
  692.   new->type = RE_REPEATED_CHAR;
  693.   new->u.repeated_char.the_repeated_char = the_char;
  694.   new->u.repeated_char.repeat_count = repeat_count;
  695.   assert (list->tail);
  696.   list->tail->next = new;
  697.   list->tail = new;
  698. }
  699.  
  700. /* Given a string, EQUIV_CLASS_STR, from a [=str=] context and
  701.    the length of that string, LEN, if LEN is exactly one, append
  702.    a newly allocated structure representing the specified
  703.    equivalence class to the specification list, LIST and return zero.
  704.    If LEN is not 1, issue an error message and return non-zero. */
  705.  
  706. static int
  707. append_equiv_class (list, equiv_class_str, len)
  708.      struct Spec_list *list;
  709.      unsigned char *equiv_class_str;
  710.      int len;
  711. {
  712.   struct List_element *new;
  713.  
  714.   if (len != 1)
  715.     {
  716.       char *tmp = make_printable_str (equiv_class_str, len);
  717.  
  718.       error (0, 0, "%s: equivalence class operand must be a single character",
  719.          tmp);
  720.       free (tmp);
  721.       return 1;
  722.     }
  723.   new = (struct List_element *) xmalloc (sizeof (struct List_element));
  724.   new->next = NULL;
  725.   new->type = RE_EQUIV_CLASS;
  726.   new->u.equiv_code = *equiv_class_str;
  727.   assert (list->tail);
  728.   list->tail->next = new;
  729.   list->tail = new;
  730.   return 0;
  731. }
  732.  
  733. /* Return a newly allocated copy of P[FIRST_IDX..LAST_IDX]. */
  734.  
  735. static unsigned char *
  736. substr (p, first_idx, last_idx)
  737.      unsigned char *p;
  738.      int first_idx;
  739.      int last_idx;
  740. {
  741.   int len = last_idx - first_idx + 1;
  742.   unsigned char *tmp = (unsigned char *) xmalloc (len);
  743.  
  744.   assert (first_idx <= last_idx);
  745.   /* We must use bcopy or memcopy rather than strncpy
  746.      because `p' may contain zero-bytes. */
  747.   bcopy (p + first_idx, tmp, len);
  748.   tmp[len] = '\0';
  749.   return tmp;
  750. }
  751.  
  752. /* Search forward starting at START_IDX for the 2-char sequence
  753.    (PRE_BRACKET_CHAR,']') in the string P of length P_LEN.  If such
  754.    a sequence is found, return the index of the first character,
  755.    otherwise return -1.  P may contain zero bytes. */
  756.  
  757. static int
  758. find_closing_delim (p, start_idx, p_len, pre_bracket_char)
  759.      unsigned char *p;
  760.      int start_idx;
  761.      int p_len;
  762.      unsigned int pre_bracket_char;
  763. {
  764.   int i;
  765.  
  766.   for (i = start_idx; i < p_len - 1; i++)
  767.     if (p[i] == pre_bracket_char && p[i + 1] == ']')
  768.       return i;
  769.   return -1;
  770. }
  771.  
  772. /* Convert a string S with explicit length LEN, possibly
  773.    containing embedded zero bytes, to a long integer value.
  774.    If the string represents a negative value, a value larger
  775.    than LONG_MAX, or if all LEN characters do not represent a
  776.    valid integer, return non-zero and do not modify *VAL.
  777.    Otherwise, return zero and set *VAL to the converted value. */
  778.  
  779. static int
  780. non_neg_strtol (s, len, val)
  781.      unsigned char *s;
  782.      int len;
  783.      long int *val;
  784. {
  785.   int i;
  786.   long sum = 0;
  787.   unsigned int base;
  788.  
  789.   if (len <= 0)
  790.     return 1;
  791.   if (s[0] == '0')
  792.     base = 8;
  793.   else if (isdigit (s[0]))
  794.     base = 10;
  795.   else
  796.     return 1;
  797.  
  798.   for (i = 0; i < len; i++)
  799.     {
  800.       int c = s[i] - '0';
  801.  
  802.       if (c >= base || c < 0)
  803.     return 1;
  804.       if (i > 8 && sum > (LONG_MAX - c) / base)
  805.     return 1;
  806.       sum = sum * base + c;
  807.     }
  808.   *val = sum;
  809.   return 0;
  810. }
  811.  
  812. /* Parse the bracketed repeat-char syntax.  If the P_LEN characters
  813.    beginning with P[ START_IDX ] comprise a valid [c*n] construct,
  814.    return the character and the repeat count through the arg pointers,
  815.    CHAR_TO_REPEAT and N, and then return the index of the closing
  816.    bracket as the function value.  If the second character following
  817.    the opening bracket is not `*' or if no closing bracket can be
  818.    found, return -1.  If a closing bracket is found and the
  819.    second char is `*', but the string between the `*' and `]' isn't
  820.    empty, an octal number, or a decimal number, print an error message
  821.    and return -2. */
  822.  
  823. static int
  824. find_bracketed_repeat (p, start_idx, p_len, char_to_repeat, n)
  825.      unsigned char *p;
  826.      int start_idx;
  827.      int p_len;
  828.      unsigned int *char_to_repeat;
  829.      long int *n;
  830. {
  831.   int i;
  832.  
  833.   assert (start_idx + 1 < p_len);
  834.   if (p[start_idx + 1] != '*')
  835.     return -1;
  836.  
  837.   for (i = start_idx + 2; i < p_len; i++)
  838.     {
  839.       if (p[i] == ']')
  840.     {
  841.       unsigned char *digit_str;
  842.       int digit_str_len = i - start_idx - 2;
  843.  
  844.       *char_to_repeat = p[start_idx];
  845.       if (digit_str_len == 0)
  846.         {
  847.           /* We've matched [c*] -- no explicit repeat count. */
  848.           *n = 0;
  849.           return i;
  850.         }
  851.  
  852.       /* Here, we have found [c*s] where s should be a string
  853.          of octal or decimal digits. */
  854.       digit_str = &p[start_idx + 2];
  855.       if (non_neg_strtol (digit_str, digit_str_len, n))
  856.         {
  857.           char *tmp = make_printable_str (digit_str, digit_str_len);
  858.           error (0, 0, "invalid repeat count `%s' in [c*n] construct", tmp);
  859.           free (tmp);
  860.           return -2;
  861.         }
  862.       return i;
  863.     }
  864.     }
  865.   return -1;            /* No bracket found. */
  866. }
  867.  
  868. /* Convert string UNESACPED_STRING (which has been preprocessed to
  869.    convert backslash-escape sequences) of length LEN characters into
  870.    a linked list of the following 5 types of constructs:
  871.       - [:str:] Character class where `str' is one of the 12 valid strings.
  872.       - [=c=] Equivalence class where `c' is any single character.
  873.       - [c*n] Repeat the single character `c' `n' times. n may be omitted.
  874.       However, if `n' is present, it must be a non-negative octal or
  875.       decimal integer.
  876.       - r-s Range of characters from `r' to `s'.  The second endpoint must
  877.       not precede the first in the current collating sequence.
  878.       - c Any other character is interpreted as itself. */
  879.  
  880. static int
  881. build_spec_list (unescaped_string, len, result)
  882.      unsigned char *unescaped_string;
  883.      int len;
  884.      struct Spec_list *result;
  885. {
  886.   unsigned char *p;
  887.   int i;
  888.  
  889.   p = unescaped_string;
  890.  
  891.   /* The main for-loop below recognizes the 4 multi-character constructs.
  892.      A character that matches (in its context) none of the multi-character
  893.      constructs is classified as `normal'.  Since all multi-character
  894.      constructs have at least 3 characters, any strings of length 2 or
  895.      less are composed solely of normal characters.  Hence, the index of
  896.      the outer for-loop runs only as far as LEN-2. */
  897.  
  898.   for (i = 0; i < len - 2;)
  899.     {
  900.       switch (p[i])
  901.     {
  902.       int fall_through;
  903.     case '[':
  904.       fall_through = 0;
  905.       switch (p[i + 1])
  906.         {
  907.           int closing_delim_idx;
  908.           int closing_bracket_idx;
  909.           unsigned int char_to_repeat;
  910.           long repeat_count;
  911.         case ':':
  912.         case '=':
  913.           closing_delim_idx = find_closing_delim (p, i + 2, len, p[i + 1]);
  914.           if (closing_delim_idx >= 0)
  915.         {
  916.           int parse_failed;
  917.           unsigned char *opnd_str = substr (p, i + 2, closing_delim_idx - 1);
  918.           if (p[i + 1] == ':')
  919.             parse_failed = append_char_class (result, opnd_str,
  920.                      (closing_delim_idx - 1) - (i + 2) + 1);
  921.           else
  922.             parse_failed = append_equiv_class (result, opnd_str,
  923.                      (closing_delim_idx - 1) - (i + 2) + 1);
  924.           free (opnd_str);
  925.  
  926.           /* Return non-zero if append_*_class reports a problem. */
  927.           if (parse_failed)
  928.             return 1;
  929.           else
  930.             i = closing_delim_idx + 2;
  931.           break;
  932.         }
  933.           /* Else fall through.  This could be [:*] or [=*]. */
  934.         default:
  935.           /* Determine whether this is a bracketed repeat range
  936.          matching the RE \[.\*(dec_or_oct_number)?\]. */
  937.           closing_bracket_idx = find_bracketed_repeat (p, i + 1,
  938.                        len, &char_to_repeat, &repeat_count);
  939.           if (closing_bracket_idx >= 0)
  940.         {
  941.           append_repeated_char (result, char_to_repeat, repeat_count);
  942.           i = closing_bracket_idx + 1;
  943.           break;
  944.         }
  945.           else if (closing_bracket_idx == -1)
  946.         {
  947.           fall_through = 1;
  948.         }
  949.           else
  950.         /* Found a string that looked like [c*n] but the
  951.            numeric part was invalid. */
  952.         return 1;
  953.           break;
  954.         }
  955.       if (!fall_through)
  956.         break;
  957.  
  958.       /* Here if we've tried to match [c*n], [:str:], and [=c=]
  959.          and none of them fit.  So we still have to consider the
  960.          range `[-c' (from `[' to `c'). */
  961.     default:
  962.       /* Look ahead one char for ranges like a-z. */
  963.       if (p[i + 1] == '-')
  964.         {
  965.           if (append_range (result, p[i], p[i + 2]))
  966.         return 1;
  967.           i += 3;
  968.         }
  969.       else
  970.         {
  971.           append_normal_char (result, p[i]);
  972.           ++i;
  973.         }
  974.       break;
  975.     }
  976.     }
  977.  
  978.   /* Now handle the (2 or fewer) remaining characters p[i]..p[len - 1]. */
  979.   for (; i < len; i++)
  980.     append_normal_char (result, p[i]);
  981.  
  982.   return 0;
  983. }
  984.  
  985.  
  986. /* Given a Spec_list S (with its saved state implicit in the values
  987.    of its members `tail' and `state'), return the next single character
  988.    in the expansion of S's constructs.  If the last character of S was
  989.    returned on the previous call or if S was empty, this function
  990.    returns -1.  For example, successive calls to get_next where S
  991.    represents the spec-string 'a-d[y*3]' will return the sequence
  992.    of values a, b, c, d, y, y, y, -1.  Finally, if the construct from
  993.    which the returned character comes is [:upper:] or [:lower:], the
  994.    parameter CLASS is given a value to indicate which it was.  Otherwise
  995.    CLASS is set to UL_NONE.  This value is used only when constructing
  996.    the translation table to verify that any occurrences of upper and
  997.    lower class constructs in the spec-strings appear in the same relative
  998.    positions. */
  999.  
  1000. static int
  1001. get_next (s, class)
  1002.      struct Spec_list *s;
  1003.      enum Upper_Lower_class *class;
  1004. {
  1005.   struct List_element *p;
  1006.   int return_val;
  1007.   int i;
  1008.  
  1009.   return_val = -1;        /* Appease the compiler. */
  1010.   if (class)
  1011.     *class = UL_NONE;
  1012.  
  1013.   if (s->state == BEGIN_STATE)
  1014.     {
  1015.       s->tail = s->head->next;
  1016.       s->state = NEW_ELEMENT;
  1017.     }
  1018.  
  1019.   p = s->tail;
  1020.   if (p == NULL)
  1021.     return -1;
  1022.  
  1023.   switch (p->type)
  1024.     {
  1025.     case RE_NORMAL_CHAR:
  1026.       return_val = p->u.normal_char;
  1027.       s->state = NEW_ELEMENT;
  1028.       s->tail = p->next;
  1029.       break;
  1030.  
  1031.     case RE_RANGE:
  1032.       if (s->state == NEW_ELEMENT)
  1033.     s->state = ORD (p->u.range.first_char);
  1034.       else
  1035.     ++(s->state);
  1036.       return_val = CHR (s->state);
  1037.       if (s->state == ORD (p->u.range.last_char))
  1038.     {
  1039.       s->tail = p->next;
  1040.       s->state = NEW_ELEMENT;
  1041.     }
  1042.       break;
  1043.  
  1044.     case RE_CHAR_CLASS:
  1045.       if (s->state == NEW_ELEMENT)
  1046.     {
  1047.       for (i = 0; i < N_CHARS; i++)
  1048.         if (is_char_class_member (p->u.char_class, i))
  1049.           break;
  1050.       assert (i < N_CHARS);
  1051.       s->state = i;
  1052.     }
  1053.       assert (is_char_class_member (p->u.char_class, s->state));
  1054.       return_val = CHR (s->state);
  1055.       for (i = s->state + 1; i < N_CHARS; i++)
  1056.     if (is_char_class_member (p->u.char_class, i))
  1057.       break;
  1058.       if (i < N_CHARS)
  1059.     s->state = i;
  1060.       else
  1061.     {
  1062.       s->tail = p->next;
  1063.       s->state = NEW_ELEMENT;
  1064.     }
  1065.       if (class)
  1066.     {
  1067.       switch (p->u.char_class)
  1068.         {
  1069.         case CC_LOWER:
  1070.           *class = UL_LOWER;
  1071.           break;
  1072.         case CC_UPPER:
  1073.           *class = UL_UPPER;
  1074.           break;
  1075.         default:
  1076.           /* empty */
  1077.           break;
  1078.         }
  1079.     }
  1080.       break;
  1081.  
  1082.     case RE_EQUIV_CLASS:
  1083.       /* FIXME: this assumes that each character is alone in its own
  1084.      equivalence class (which appears to be correct for my
  1085.      LC_COLLATE.  But I don't know of any function that allows
  1086.      one to determine a character's equivalence class. */
  1087.  
  1088.       return_val = p->u.equiv_code;
  1089.       s->state = NEW_ELEMENT;
  1090.       s->tail = p->next;
  1091.       break;
  1092.  
  1093.     case RE_REPEATED_CHAR:
  1094.       /* Here, a repeat count of n == 0 means don't repeat at all. */
  1095.       assert (p->u.repeated_char.repeat_count >= 0);
  1096.       if (p->u.repeated_char.repeat_count == 0)
  1097.     {
  1098.       s->tail = p->next;
  1099.       s->state = NEW_ELEMENT;
  1100.       return_val = get_next (s, class);
  1101.     }
  1102.       else
  1103.     {
  1104.       if (s->state == NEW_ELEMENT)
  1105.         {
  1106.           s->state = 0;
  1107.         }
  1108.       ++(s->state);
  1109.       return_val = p->u.repeated_char.the_repeated_char;
  1110.       if (p->u.repeated_char.repeat_count > 0
  1111.           && s->state == p->u.repeated_char.repeat_count)
  1112.         {
  1113.           s->tail = p->next;
  1114.           s->state = NEW_ELEMENT;
  1115.         }
  1116.     }
  1117.       break;
  1118.  
  1119.     case RE_NO_TYPE:
  1120.       assert (0);
  1121.       break;
  1122.     }
  1123.   return return_val;
  1124. }
  1125.  
  1126. /* This is a minor kludge.  This function is called from
  1127.    get_spec_stats to determine the cardinality of a set derived
  1128.    from a complemented string.  It's a kludge in that some of
  1129.    the same operations are (duplicated) performed in set_initialize. */
  1130.  
  1131. static int
  1132. card_of_complement (s)
  1133.      struct Spec_list *s;
  1134. {
  1135.   int c;
  1136.   int cardinality = N_CHARS;
  1137.   SET_TYPE in_set[N_CHARS];
  1138.  
  1139.   bzero (in_set, N_CHARS * sizeof (in_set[0]));
  1140.   s->state = BEGIN_STATE;
  1141.   while ((c = get_next (s, NULL)) != -1)
  1142.     if (!in_set[c]++)
  1143.       --cardinality;
  1144.   return cardinality;
  1145. }
  1146.  
  1147. /* Gather statistics about the spec-list S in preparation for the tests
  1148.    in validate that determine the legality of the specs.  This function
  1149.    is called at most twice; once for string1, and again for any string2.
  1150.    LEN_S1 < 0 indicates that this is the first call and that S represents
  1151.    string1.  When LEN_S1 >= 0, it is the length of the expansion of the
  1152.    constructs in string1, and we can use its value to resolve any
  1153.    indefinite repeat construct in S (which represents string2).  Hence,
  1154.    this function has the side-effect that it converts a valid [c*]
  1155.    construct in string2 to [c*n] where n is large enough (or 0) to give
  1156.    string2 the same length as string1.  For example, with the command
  1157.    tr a-z 'A[\n*]Z' on the second call to get_spec_stats, LEN_S1 would
  1158.    be 26 and S (representing string2) would be converted to 'A[\n*24]Z'. */
  1159.  
  1160. static void
  1161. get_spec_stats (s, len_s1)
  1162.      struct Spec_list *s;
  1163.      int len_s1;
  1164. {
  1165.   struct List_element *p;
  1166.   struct List_element *indefinite_repeat_element = NULL;
  1167.   int len = 0;
  1168.  
  1169.   s->n_indefinite_repeats = 0;
  1170.   s->has_equiv_class = 0;
  1171.   s->has_restricted_char_class = 0;
  1172.   s->has_upper_or_lower = 0;
  1173.   for (p = s->head->next; p; p = p->next)
  1174.     {
  1175.       switch (p->type)
  1176.     {
  1177.       int i;
  1178.     case RE_NORMAL_CHAR:
  1179.       ++len;
  1180.       break;
  1181.  
  1182.     case RE_RANGE:
  1183.       assert (p->u.range.last_char > p->u.range.first_char);
  1184.       len += p->u.range.last_char - p->u.range.first_char + 1;
  1185.       break;
  1186.  
  1187.     case RE_CHAR_CLASS:
  1188.       for (i = 0; i < N_CHARS; i++)
  1189.         if (is_char_class_member (p->u.char_class, i))
  1190.           ++len;
  1191.       switch (p->u.char_class)
  1192.         {
  1193.         case CC_UPPER:
  1194.         case CC_LOWER:
  1195.           s->has_upper_or_lower = 1;
  1196.           break;
  1197.         default:
  1198.           s->has_restricted_char_class = 1;
  1199.           break;
  1200.         }
  1201.       break;
  1202.  
  1203.     case RE_EQUIV_CLASS:
  1204.       for (i = 0; i < N_CHARS; i++)
  1205.         if (is_equiv_class_member (p->u.equiv_code, i))
  1206.           ++len;
  1207.       s->has_equiv_class = 1;
  1208.       break;
  1209.  
  1210.     case RE_REPEATED_CHAR:
  1211.       if (p->u.repeated_char.repeat_count > 0)
  1212.         len += p->u.repeated_char.repeat_count;
  1213.       else if (p->u.repeated_char.repeat_count == 0)
  1214.         {
  1215.           indefinite_repeat_element = p;
  1216.           ++(s->n_indefinite_repeats);
  1217.         }
  1218.       break;
  1219.  
  1220.     case RE_NO_TYPE:
  1221.       assert (0);
  1222.       break;
  1223.     }
  1224.     }
  1225.  
  1226.   if (len_s1 >= len && s->n_indefinite_repeats == 1)
  1227.     {
  1228.       indefinite_repeat_element->u.repeated_char.repeat_count = len_s1 - len;
  1229.       len = len_s1;
  1230.     }
  1231.   if (complement && len_s1 < 0)
  1232.     s->length = card_of_complement (s);
  1233.   else
  1234.     s->length = len;
  1235.   return;
  1236. }
  1237.  
  1238. static void
  1239. spec_init (spec_list)
  1240.      struct Spec_list *spec_list;
  1241. {
  1242.   spec_list->head = spec_list->tail =
  1243.     (struct List_element *) xmalloc (sizeof (struct List_element));
  1244.   spec_list->head->next = NULL;
  1245. }
  1246.  
  1247. /* This function makes two passes over the argument string S.  The first
  1248.    one converts all \c and \ddd escapes to their one-byte representations.
  1249.    The second constructs a linked specification list, SPEC_LIST, of the
  1250.    characters and constructs that comprise the argument string.  If either
  1251.    of these passes detects an error, this function returns non-zero. */
  1252.  
  1253. static int
  1254. parse_str (s, spec_list)
  1255.      unsigned char *s;
  1256.      struct Spec_list *spec_list;
  1257. {
  1258.   int len;
  1259.  
  1260.   if (unquote (s, &len))
  1261.     return 1;
  1262.   if (build_spec_list (s, len, spec_list))
  1263.     return 1;
  1264.   return 0;
  1265. }
  1266.  
  1267. /* Given two specification lists, S1 and S2, and assuming that
  1268.    S1->length > S2->length, append a single [c*n] element to S2 where c
  1269.    is the last character in the expansion of S2 and n is the difference
  1270.    between the two lengths.
  1271.    Upon successful completion, S2->length is set to S1->length.  The only
  1272.    way this function can fail to make S2 as long as S1 is when S2 has
  1273.    zero-length, since in that case, there is no last character to repeat.
  1274.  
  1275.    Providing this functionality allows the user to do some pretty
  1276.    non-BSD (and non-portable) things:  For example, the command
  1277.        tr -cs '[:upper:]0-9' '[:lower:]'
  1278.    is almost guaranteed to give results that depend on your collating
  1279.    sequence.  */
  1280.  
  1281. static void
  1282. string2_extend (s1, s2)
  1283.      struct Spec_list *s1;
  1284.      struct Spec_list *s2;
  1285. {
  1286.   struct List_element *p;
  1287.   int char_to_repeat;
  1288.   int i;
  1289.  
  1290.   assert (translating);
  1291.   assert (s1->length > s2->length);
  1292.   if (s2->length == 0)
  1293.     return;
  1294.  
  1295.   char_to_repeat = -1;        /* Appease the compiler. */
  1296.   p = s2->tail;
  1297.   switch (p->type)
  1298.     {
  1299.     case RE_NORMAL_CHAR:
  1300.       char_to_repeat = p->u.normal_char;
  1301.       break;
  1302.     case RE_RANGE:
  1303.       char_to_repeat = p->u.range.last_char;
  1304.       break;
  1305.     case RE_CHAR_CLASS:
  1306.       for (i = N_CHARS; i >= 0; i--)
  1307.     if (is_char_class_member (p->u.char_class, i))
  1308.       break;
  1309.       assert (i >= 0);
  1310.       char_to_repeat = CHR (i);
  1311.       break;
  1312.     case RE_EQUIV_CLASS:
  1313.       /* This shouldn't happen, because validate exits with an error
  1314.      if it finds an equiv class in string2 when translating. */
  1315.       assert (0);
  1316.       break;
  1317.     case RE_REPEATED_CHAR:
  1318.       char_to_repeat = p->u.repeated_char.the_repeated_char;
  1319.       break;
  1320.     case RE_NO_TYPE:
  1321.       assert (0);
  1322.       break;
  1323.     }
  1324.   append_repeated_char (s2, char_to_repeat, s1->length - s2->length);
  1325.   s2->length = s1->length;
  1326.   return;
  1327. }
  1328.  
  1329. /* Die with an error message if S1 and S2 describe strings that
  1330.    are not valid with the given command line switches.
  1331.    A side effect of this function is that if a legal [c*] or
  1332.    [c*0] construct appears in string2, it is converted to [c*n]
  1333.    with a value for n that makes s2->length == s1->length.  By
  1334.    the same token, if the --truncate-set1 option is not
  1335.    given, S2 may be extended. */
  1336.  
  1337. static void
  1338. validate (s1, s2)
  1339.      struct Spec_list *s1;
  1340.      struct Spec_list *s2;
  1341. {
  1342.   get_spec_stats (s1, -1);
  1343.   if (s1->n_indefinite_repeats > 0)
  1344.     {
  1345.       error (1, 0, "the [c*] repeat construct may not appear in string1");
  1346.     }
  1347.  
  1348.   /* FIXME: it isn't clear from the POSIX spec that this is illegal,
  1349.      but in the spirit of the other restrictions put on translation
  1350.      with character classes, this seems a logical interpretation. */
  1351.   if (complement && s1->has_upper_or_lower)
  1352.     {
  1353.       error (1, 0,
  1354.          "character classes may not be used when translating and complementing");
  1355.     }
  1356.  
  1357.   if (s2)
  1358.     {
  1359.       get_spec_stats (s2, s1->length);
  1360.       if (s2->has_restricted_char_class)
  1361.     {
  1362.       error (1, 0,
  1363.          "when translating, the only character classes that may appear in\n\
  1364. \tstring2 are `upper' and `lower'");
  1365.     }
  1366.  
  1367.       if (s2->n_indefinite_repeats > 1)
  1368.     {
  1369.       error (1, 0, "only one [c*] repeat construct may appear in string2");
  1370.     }
  1371.  
  1372.       if (translating)
  1373.     {
  1374.       if (s2->has_equiv_class)
  1375.         {
  1376.           error (1, 0,
  1377.              "[=c=] expressions may not appear in string2 when translating");
  1378.         }
  1379.  
  1380.       if (s1->length > s2->length)
  1381.         {
  1382.           if (!truncate_set1)
  1383.         string2_extend (s1, s2);
  1384.         }
  1385.  
  1386.       if (complement && s2->has_upper_or_lower)
  1387.         error (1, 0,
  1388.            "character classes may not be used when translating and complementing");
  1389.     }
  1390.       else
  1391.     /* Not translating. */
  1392.     {
  1393.       if (s2->n_indefinite_repeats > 0)
  1394.         error (1, 0,
  1395.            "the [c*] construct may appear in string2 only when translating");
  1396.     }
  1397.     }
  1398. }
  1399.  
  1400. /* Read buffers of SIZE bytes via the function READER (if READER is
  1401.    NULL, read from stdin) until EOF.  When non-NULL, READER is either
  1402.    read_and_delete or read_and_xlate.  After each buffer is read, it is
  1403.    processed and written to stdout.  The buffers are processed so that
  1404.    multiple consecutive occurrences of the same character in the input
  1405.    stream are replaced by a single occurrence of that character if the
  1406.    character is in the squeeze set. */
  1407.  
  1408. static void
  1409. squeeze_filter (buf, size, reader)
  1410.      unsigned char *buf;
  1411.      long int size;
  1412.      PFI reader;
  1413. {
  1414.   unsigned int char_to_squeeze = NOT_A_CHAR;
  1415.   int i = 0;
  1416.   int nr = 0;
  1417.  
  1418.   for (;;)
  1419.     {
  1420.       int begin;
  1421.  
  1422.       if (i >= nr)
  1423.     {
  1424.       if (reader == NULL)
  1425.         nr = read (0, (char *) buf, size);
  1426.       else
  1427.         nr = (*reader) (buf, size, NULL);
  1428.  
  1429.       if (nr < 0)
  1430.         error (1, errno, "read error");
  1431.       if (nr == 0)
  1432.         break;
  1433.       i = 0;
  1434.     }
  1435.  
  1436.       begin = i;
  1437.  
  1438.       if (char_to_squeeze == NOT_A_CHAR)
  1439.     {
  1440.       int out_len;
  1441.       /* Here, by being a little tricky, we can get a significant
  1442.          performance increase in most cases when the input is
  1443.          reasonably large.  Since tr will modify the input only
  1444.          if two consecutive (and identical) input characters are
  1445.          in the squeeze set, we can step by two through the data
  1446.          when searching for a character in the squeeze set.  This
  1447.          means there may be a little more work in a few cases and
  1448.          perhaps twice as much work in the worst cases where most
  1449.          of the input is removed by squeezing repeats.  But most
  1450.          uses of this functionality seem to remove less than 20-30%
  1451.          of the input. */
  1452.       for (; i < nr && !in_squeeze_set[buf[i]]; i += 2)
  1453.         ;            /* empty */
  1454.  
  1455.       /* There is a special case when i == nr and we've just
  1456.          skipped a character (the last one in buf) that is in
  1457.          the squeeze set. */
  1458.       if (i == nr && in_squeeze_set[buf[i - 1]])
  1459.         --i;
  1460.  
  1461.       if (i >= nr)
  1462.         out_len = nr - begin;
  1463.       else
  1464.         {
  1465.           char_to_squeeze = buf[i];
  1466.           /* We're about to output buf[begin..i]. */
  1467.           out_len = i - begin + 1;
  1468.  
  1469.           /* But since we stepped by 2 in the loop above,
  1470.          out_len may be one too large. */
  1471.           if (i > 0 && buf[i - 1] == char_to_squeeze)
  1472.         --out_len;
  1473.  
  1474.           /* Advance i to the index of first character to be
  1475.          considered when looking for a char different from
  1476.          char_to_squeeze. */
  1477.           ++i;
  1478.         }
  1479.       if (out_len > 0
  1480.           && fwrite ((char *) &buf[begin], 1, out_len, stdout) == 0)
  1481.         error (1, errno, "write error");
  1482.     }
  1483.  
  1484.       if (char_to_squeeze != NOT_A_CHAR)
  1485.     {
  1486.       /* Advance i to index of first char != char_to_squeeze
  1487.          (or to nr if all the rest of the characters in this
  1488.          buffer are the same as char_to_squeeze). */
  1489.       for (; i < nr && buf[i] == char_to_squeeze; i++)
  1490.         ;            /* empty */
  1491.       if (i < nr)
  1492.         char_to_squeeze = NOT_A_CHAR;
  1493.       /* If (i >= nr) we've squeezed the last character in this buffer.
  1494.          So now we have to read a new buffer and continue comparing
  1495.          characters against char_to_squeeze. */
  1496.     }
  1497.     }
  1498. }
  1499.  
  1500. /* Read buffers of SIZE bytes from stdin until one is found that
  1501.    contains at least one character not in the delete set.  Store
  1502.    in the array BUF, all characters from that buffer that are not
  1503.    in the delete set, and return the number of characters saved
  1504.    or 0 upon EOF. */
  1505.  
  1506. static long
  1507. read_and_delete (buf, size, not_used)
  1508.      unsigned char *buf;
  1509.      long int size;
  1510.      PFI not_used;
  1511. {
  1512.   long n_saved;
  1513.   static int hit_eof = 0;
  1514.  
  1515.   assert (not_used == NULL);
  1516.   assert (size > 0);
  1517.  
  1518.   if (hit_eof)
  1519.     return 0;
  1520.  
  1521.   /* This enclosing do-while loop is to make sure that
  1522.      we don't return zero (indicating EOF) when we've
  1523.      just deleted all the characters in a buffer. */
  1524.   do
  1525.     {
  1526.       int i;
  1527.       int nr = read (0, (char *) buf, size);
  1528.  
  1529.       if (nr < 0)
  1530.     error (1, errno, "read error");
  1531.       if (nr == 0)
  1532.     {
  1533.       hit_eof = 1;
  1534.       return 0;
  1535.     }
  1536.  
  1537.       /* This first loop may be a waste of code, but gives much
  1538.          better performance when no characters are deleted in
  1539.          the beginning of a buffer.  It just avoids the copying
  1540.          of buf[i] into buf[n_saved] when it would be a NOP. */
  1541.  
  1542.       for (i = 0; i < nr && !in_delete_set[buf[i]]; i++)
  1543.     /* empty */ ;
  1544.       n_saved = i;
  1545.  
  1546.       for (++i; i < nr; i++)
  1547.     if (!in_delete_set[buf[i]])
  1548.       buf[n_saved++] = buf[i];
  1549.     }
  1550.   while (n_saved == 0);
  1551.  
  1552.   return n_saved;
  1553. }
  1554.  
  1555. /* Read at most SIZE bytes from stdin into the array BUF.  Then
  1556.    perform the in-place and one-to-one mapping specified by the global
  1557.    array `xlate'.  Return the number of characters read, or 0 upon EOF. */
  1558.  
  1559. static long
  1560. read_and_xlate (buf, size, not_used)
  1561.      unsigned char *buf;
  1562.      long int size;
  1563.      PFI not_used;
  1564. {
  1565.   long chars_read = 0;
  1566.   static int hit_eof = 0;
  1567.   int i;
  1568.  
  1569.   assert (not_used == NULL);
  1570.   assert (size > 0);
  1571.  
  1572.   if (hit_eof)
  1573.     return 0;
  1574.  
  1575.   chars_read = read (0, (char *) buf, size);
  1576.   if (chars_read < 0)
  1577.     error (1, errno, "read error");
  1578.   if (chars_read == 0)
  1579.     {
  1580.       hit_eof = 1;
  1581.       return 0;
  1582.     }
  1583.  
  1584.   for (i = 0; i < chars_read; i++)
  1585.     buf[i] = xlate[buf[i]];
  1586.  
  1587.   return chars_read;
  1588. }
  1589.  
  1590. /* Initialize a boolean membership set IN_SET with the character
  1591.    values obtained by traversing the linked list of constructs S
  1592.    using the function `get_next'.  If COMPLEMENT_THIS_SET is
  1593.    non-zero the resulting set is complemented. */
  1594.  
  1595. static void
  1596. set_initialize (s, complement_this_set, in_set)
  1597.      struct Spec_list *s;
  1598.      int complement_this_set;
  1599.      SET_TYPE *in_set;
  1600. {
  1601.   int c;
  1602.   int i;
  1603.  
  1604.   bzero (in_set, N_CHARS * sizeof (in_set[0]));
  1605.   s->state = BEGIN_STATE;
  1606.   while ((c = get_next (s, NULL)) != -1)
  1607.     in_set[c] = 1;
  1608.   if (complement_this_set)
  1609.     for (i = 0; i < N_CHARS; i++)
  1610.       in_set[i] = (!in_set[i]);
  1611. }
  1612.  
  1613. void
  1614. main (argc, argv)
  1615.      int argc;
  1616.      char **argv;
  1617. {
  1618.   int c;
  1619.   int non_option_args;
  1620.   struct Spec_list buf1, buf2;
  1621.   struct Spec_list *s1 = &buf1;
  1622.   struct Spec_list *s2 = &buf2;
  1623.  
  1624.   program_name = argv[0];
  1625.  
  1626.   while ((c = getopt_long (argc, argv, "cdst", long_options,
  1627.                (int *) 0)) != EOF)
  1628.     {
  1629.       switch (c)
  1630.     {
  1631.     case 0:
  1632.       break;
  1633.  
  1634.     case 'c':
  1635.       complement = 1;
  1636.       break;
  1637.  
  1638.     case 'd':
  1639.       delete = 1;
  1640.       break;
  1641.  
  1642.     case 's':
  1643.       squeeze_repeats = 1;
  1644.       break;
  1645.  
  1646.     case 't':
  1647.       truncate_set1 = 1;
  1648.       break;
  1649.  
  1650.     default:
  1651.       usage ();
  1652.       break;
  1653.     }
  1654.     }
  1655.  
  1656.   posix_pedantic = (getenv ("POSIXLY_CORRECT") != 0);
  1657.  
  1658.   non_option_args = argc - optind;
  1659.   translating = (non_option_args == 2 && !delete);
  1660.  
  1661.   /* Change this test if it is legal to give tr no options and
  1662.      no args at all.  POSIX doesn't specifically say anything
  1663.      either way, but it looks like they implied it's illegal
  1664.      by omission.  If you want to make tr do a slow imitation
  1665.      of `cat' use `tr a a'. */
  1666.   if (non_option_args > 2)
  1667.     usage ();
  1668.  
  1669.   if (!delete && !squeeze_repeats && non_option_args != 2)
  1670.     error (1, 0, "two strings must be given when translating");
  1671.  
  1672.   if (delete && squeeze_repeats && non_option_args != 2)
  1673.     error (1, 0, "two strings must be given when both \
  1674. deleting and squeezing repeats");
  1675.  
  1676.   /* If --delete is given without --squeeze-repeats, then
  1677.      only one string argument may be specified.  But POSIX
  1678.      says to ignore any string2 in this case, so if POSIXLY_CORRECT
  1679.      is set, pretend we never saw string2.  But I think
  1680.      this deserves a fatal error, so that's the default. */
  1681.   if ((delete && !squeeze_repeats) && non_option_args != 1)
  1682.     {
  1683.       if (posix_pedantic && non_option_args == 2)
  1684.     --non_option_args;
  1685.       else
  1686.     error (1, 0,
  1687.            "only one string may be given when deleting without squeezing repeats");
  1688.     }
  1689.  
  1690.   spec_init (s1);
  1691.   if (parse_str ((unsigned char *) argv[optind], s1))
  1692.     exit (1);
  1693.  
  1694.   if (non_option_args == 2)
  1695.     {
  1696.       spec_init (s2);
  1697.       if (parse_str ((unsigned char *) argv[optind + 1], s2))
  1698.     exit (1);
  1699.     }
  1700.   else
  1701.     s2 = NULL;
  1702.  
  1703.   validate (s1, s2);
  1704.  
  1705.   if (squeeze_repeats && non_option_args == 1)
  1706.     {
  1707.       set_initialize (s1, complement, in_squeeze_set);
  1708.       squeeze_filter (io_buf, IO_BUF_SIZE, NULL);
  1709.     }
  1710.   else if (delete && non_option_args == 1)
  1711.     {
  1712.       int nr;
  1713.  
  1714.       set_initialize (s1, complement, in_delete_set);
  1715.       do
  1716.     {
  1717.       nr = read_and_delete (io_buf, IO_BUF_SIZE, NULL);
  1718.       if (nr > 0 && fwrite ((char *) io_buf, 1, nr, stdout) == 0)
  1719.         error (1, errno, "write error");
  1720.     }
  1721.       while (nr > 0);
  1722.     }
  1723.   else if (squeeze_repeats && delete && non_option_args == 2)
  1724.     {
  1725.       set_initialize (s1, complement, in_delete_set);
  1726.       set_initialize (s2, 0, in_squeeze_set);
  1727.       squeeze_filter (io_buf, IO_BUF_SIZE, (PFI) read_and_delete);
  1728.     }
  1729.   else if (translating)
  1730.     {
  1731.       if (complement)
  1732.     {
  1733.       int i;
  1734.       SET_TYPE *in_s1 = in_delete_set;
  1735.  
  1736.       set_initialize (s1, 0, in_s1);
  1737.       s2->state = BEGIN_STATE;
  1738.       for (i = 0; i < N_CHARS; i++)
  1739.         xlate[i] = i;
  1740.       for (i = 0; i < N_CHARS; i++)
  1741.         {
  1742.           if (!in_s1[i])
  1743.         {
  1744.           int c = get_next (s2, NULL);
  1745.           assert (c != -1 || truncate_set1);
  1746.           if (c == -1)
  1747.             {
  1748.               /* This will happen when tr is invoked like e.g.
  1749.              tr -cs A-Za-z0-9 '\012'.  */
  1750.               break;
  1751.             }
  1752.           xlate[i] = c;
  1753.         }
  1754.         }
  1755.       assert (get_next (s2, NULL) == -1 || truncate_set1);
  1756.     }
  1757.       else
  1758.     {
  1759.       int c1, c2;
  1760.       int i;
  1761.       enum Upper_Lower_class class_s1;
  1762.       enum Upper_Lower_class class_s2;
  1763.  
  1764.       for (i = 0; i < N_CHARS; i++)
  1765.         xlate[i] = i;
  1766.       s1->state = BEGIN_STATE;
  1767.       s2->state = BEGIN_STATE;
  1768.       for (;;)
  1769.         {
  1770.           c1 = get_next (s1, &class_s1);
  1771.           c2 = get_next (s2, &class_s2);
  1772.           if (!class_ok[(int) class_s1][(int) class_s2])
  1773.         error (1, 0,
  1774.             "misaligned or mismatched upper and/or lower classes");
  1775.           /* The following should have been checked by validate... */
  1776.           if (c2 == -1)
  1777.         break;
  1778.           xlate[c1] = c2;
  1779.         }
  1780.       assert (c1 == -1 || truncate_set1);
  1781.     }
  1782.       if (squeeze_repeats)
  1783.     {
  1784.       set_initialize (s2, 0, in_squeeze_set);
  1785.       squeeze_filter (io_buf, IO_BUF_SIZE, (PFI) read_and_xlate);
  1786.     }
  1787.       else
  1788.     {
  1789.       int chars_read;
  1790.  
  1791.       do
  1792.         {
  1793.           chars_read = read_and_xlate (io_buf, IO_BUF_SIZE, NULL);
  1794.           if (chars_read > 0
  1795.           && fwrite ((char *) io_buf, 1, chars_read, stdout) == 0)
  1796.         error (1, errno, "write error");
  1797.         }
  1798.       while (chars_read > 0);
  1799.     }
  1800.     }
  1801.  
  1802.   exit (0);
  1803. }
  1804.  
  1805.